﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimpleRest.Serialization
{
    public class FormSerializer
    {
        public FormSerializer() { }

        public string Serialize<T>()
        {
            return this.Serialize(typeof(T));
        }
        public string Serialize(object obj)
        {
            if (obj == null)
                return string.Empty;

            StringBuilder sb = new StringBuilder();
            Type type = obj.GetType();

            foreach (var property in type.GetProperties())
            {
                object propertyValue = property.GetValue(obj, null);
                if (TypeCache.IsPrimiviteType(property.PropertyType))
                {
                    sb.Append(property.PropertyType.Name).Append("=").Append(propertyValue.ToString()).Append("&");
                }
                else
                {
                    sb.Append(this.Serialize(propertyValue));
                }
            }

            return sb.ToString().TrimEnd(new char[] { '&' });
        }
    }
}
